/*****************************************************************************
 * Copyright (C) 2009 Gwathuirim
 *
 * This is free software; you can redistribute it and/or modify it under the
 * terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 3 of the License, or (at your option) any later
 * version.
 *
 * This is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Public License for more details
 *
 * To obtain a copy of the GNU General Public License, please see
 * <http://www.gnu.org.licenses/>
 *****************************************************************************/

// ==UserScript==
// @name           Imperion - MiningHelper
// @namespace      http://code.google.com/p/imperion-gm/
// @include        http://*.imperion.*/map*
// @include        http://*.imperion.*/fleetBase/*
// @include        http://*.imperion.*/researchCenter*
// @require        http://imperion-gm.googlecode.com/svn/trunk/backup/imperion_timeline_0.07/jquery-latest.js
// @require        http://imperion-gm.googlecode.com/svn/trunk/backup/imperion_timeline_0.07/patch.js
// @require        http://imperion-gm.googlecode.com/svn/trunk/backup/imperion_timeline_0.07/date.js
// @require        http://imperion-gm.googlecode.com/svn/trunk/backup/imperion_timeline_0.07/feature.js
// @require        http://imperion-gm.googlecode.com/svn/trunk/resources/settings.js
// @require        http://imperion-gm.googlecode.com/svn/trunk/backup/imperion_timeline_0.07/events.js
// @require        http://imperion-gm.googlecode.com/svn/trunk/resources/jquery.countdown.js
// @require		   http://stevenlevithan.com/assets/misc/date.format.js
// ==/UserScript==

(function() {

/**********************************************************************************/
/** Language support **************************************************************/
/**********************************************************************************/

/* language entries */
var language = new Object();

/* German */
/* For the *.imperion.de servers */
language['de'] = new Object();
language['de']['comets'] 				= "Kometen";
language['de']['debris'] 				= "Trümmerfelder";
language['de']['asteroids'] 			= "Asteroiden";
language['de']['metal'] 				= "Metall";
language['de']['crystal'] 				= "Kristall";
language['de']['deuterium'] 			= "Deuterium";
language['de']['tritium'] 				= "Tritium";
language['de']['coordinates'] 			= "Koordinaten";
language['de']['distance'] 				= "Entfernung";
language['de']['resourceSpot'] 			= "Rohstoffvorkommen";
language['de']['recycleDuration'] 		= "Abbau-Dauer";
language['de']['terranSmallRecycler']	= "Kleine Recycler";
language['de']['terranBigRecycler']		= "Große Recycler";
language['de']['titanRecycler']			= "Recycler";
language['de']['xenRecycler']			= "Octopons";
language['de']['fleetEvents']			= "Flottenereignisse";
language['de']['fleetData']				= "Flottendaten";
language['de']['count']					= "Anzahl";
language['de']['cargoCapacity']			= "Laderaum";
language['de']['unit']					= "Einheit";
language['de']['flightDuration']		= "Flug-Dauer";
language['de']['event']					= "Ereignis";
language['de']['from']					= "Ursprungsort";
language['de']['duration']				= "Dauer";

/* English */
/* For the *.imperion.org servers */
language['org'] = new Object();
language['org']['comets'] 				= "Comets";
language['org']['debris'] 				= "Debris";
language['org']['asteroids'] 			= "Asteroids";
language['org']['metal'] 				= "Metal";
language['org']['crystal'] 				= "Crystal";
language['org']['deuterium'] 			= "Deuterium";
language['org']['tritium'] 				= "Tritium";
language['org']['coordinates'] 			= "Coordinates";
language['org']['distance'] 			= "Distance";
language['org']['resourceSpot'] 		= "Ressource spot";
language['org']['recycleDuration'] 		= "recycle duration";
language['org']['terranSmallRecycler']	= "Small recycler";
language['org']['terranBigRecycler']	= "Large recycler";
language['org']['titanRecycler']		= "Recycler";
language['org']['xenRecycler']			= "Octopon";
language['org']['fleetEvents']			= "fleet events";
language['org']['fleetData']			= "fleet data";
language['org']['count']				= "Anzahl";
language['org']['cargoCapacity']		= "Laderaum";
language['org']['unit']					= "Einheit";
language['org']['flightDuration']		= "Flug-Dauer";
language['org']['event']				= "Ereignis";
language['org']['from']					= "Ursprungsort";
language['org']['duration']				= "Dauer";

/* Determine TLD for language support */
var languageKey = window.location.hostname;
languageKey = languageKey.split(".");
languageKey = languageKey[languageKey.length - 1];

var currentLanguage = language[languageKey];
function $l(key) { return currentLanguage[key]; }

/**********************************************************************************/
/** Some usefull functions ********************************************************/
/**********************************************************************************/

/**
 * Needed to track the mouse position and store the position in the window.
 */
function onMouseMove(event) {
	unsafeWindow.mouseX = event.pageX;
	unsafeWindow.mouseY = event.pageY;
}
window.addEventListener("mousemove", onMouseMove, false);

/**
 * Inserts the given Html.
 */
function insertHtml(html) {
	var htmlWrapper = document.createElement("div");
	
	var htmlSource = html;
	if (isArray(htmlSource))
		htmlSource = htmlSource.join("");
		
	htmlWrapper.innerHTML = htmlSource;
	
	document.body.appendChild(htmlWrapper);
}

/**
 * Tests if the object is an Array.
 */
function isArray(obj) {
	return obj.constructor == Array;
}

/**********************************************************************************/
/** MiningHelper ******************************************************************/
/**********************************************************************************/

MiningHelper = new Object();

/* Make some page specific available */
MiningHelper.mapData = unsafeWindow['mapData'];
MiningHelper.config = unsafeWindow['config'];

MiningHelper.maxMetal = 0;
MiningHelper.maxCrystal = 0;
MiningHelper.maxDeuTri = 0;

/**
 * Initializes the MiningHelper
 */
MiningHelper.initialize = function() {
	/* find centered Coordinates and so on */
	this.centeredSystemId = this.findCenteredSystemId();
	this.centeredSystemCoords = this.config.generator.getCoordsBySystemId(this.centeredSystemId);
	
	this.findPlayerSpecies();
	this.readResearches();
	this.filterFleetEvents();
	
	/* Create internal object structure */
	this.buildCometArray();
	this.buildDebrisArray();
	this.buildAsteroidArray();
	
	/* this plugins the script into the remote page */
	this.insertListFrameAsHtml();
	this.insertInfoBoxFrameAsHtml();
	
	/* now we can insert the object list entries */
	this.insertCometListEntries();
	this.insertDebrisListEntries();
	this.insertAsteroidListEntries();
}

/**
 * Finds the species string.
 */
MiningHelper.findPlayerSpecies = function() {
	var speciesStyleSheetLink = $("link[rel=stylesheet]").eq(2).attr("href");
	this.playerSpecies = speciesStyleSheetLink.match("xen");
	if (this.playerSpecies == null)
		this.playerSpecies = speciesStyleSheetLink.match("terrans");
	if (this.playerSpecies == null)
		this.playerSpecies = speciesStyleSheetLink.match("titans");
	this.playerSpecies = this.playerSpecies[0];
}

/**
 * Reads the researches out of the GM store.
 */
MiningHelper.readResearches = function() {
	var researchesValue = GM_getValue("researches");
	if (researchesValue != undefined) {
		this.researches = JSON.parse(researchesValue);
		return;
	}
	
	this.researches = new Object();
	this.researches.cargoCapacity = 0;
	this.researches.recycling = 0;
	this.researches.fuelCapacity = 0;
	this.researches.driveEngineering = 0;
	this.researches.fuelConsumption = 0;
}

/**
 * Writes down the researches into the GM store.
 */
MiningHelper.writeResearches = function() {

	function getResearchLevel(category, researchRow) {
		return $("#categorie_" + category + "_slide>table>tbody>tr")
			.eq(researchRow)
			.find("td")
			.eq(1)
			.find(".active.bgNoRepeat.interface_content_building_info_level").length;
	}

	var researches = new Object();
	researches.cargoCapacity = getResearchLevel(4, 12);
	researches.recycling = getResearchLevel(4, 2);
	researches.fuelCapacity = getResearchLevel(4, 18);
	researches.driveEngineering = getResearchLevel(4, 8);
	researches.fuelConsumption = getResearchLevel(4, 10);
	
	GM_setValue("researches", JSON.stringify(researches));
}

/**
 * Reads the stored events and filters fleetEvents out.
 * Stores it into "this.fleetEvents" array
 */
MiningHelper.filterFleetEvents = function() {
	this.fleetEvents = new Array();
	
	//Old events are unneeded
	Events.history = 0;
	Events.call('update_data', true);
	
	Events.s.events.read();
    var events = Events.events;
    for (v in events) {
        try {
            var planet=Settings.planet_names[v];
            for (e in events[v]) {
                if (events[v][e][0] == "fleet") {
					events[v][e].push(planet);
					this.fleetEvents.push(events[v][e]);
				}
            }
        } catch (e) {
            alert(e);
        }
    }
}

/**
 * Searches for events by a spotName. Returns an array with resulting events
 */
MiningHelper.searchEventsBySpotName = function(spotName) {
	var events = new Array();
	
	for (var i = 0; i < this.fleetEvents.length; i++) {
		if (this.fleetEvents[i][2].indexOf(spotName) > 0) {
			events.push(this.fleetEvents[i]);
		}
	}
	
	return events;
}

/**
 * adds countdown divs to the events in the spotObj
 */
MiningHelper.addCountdownsFromEvents = function(spotObj) {
	spotObj.eventCountdowns = new Array();
	
	for (var i = 0; i < spotObj.events.length; i++) {
		var timeStamp = spotObj.events[i][1];
		var timeStampDate = new Date();
		timeStampDate.setTime(timeStamp);
		
		spotObj.eventCountdowns.push($.new("div").countdown({until: timeStampDate, compact: true, layout: '{hnn}{sep}{mnn}{sep}{snn}'}));
	}
}

/**
 * Finds the systemId from the system which is centered
 */
MiningHelper.findCenteredSystemId = function() {
	var scriptTags = document.getElementsByTagName("script");
	for (var i = 0; i < scriptTags.length; i++) {
		var treffer = scriptTags[i].innerHTML.match(/domready/);
		if (treffer != null) {
			return scriptTags[i].innerHTML.match(/\d+/);
		}
	}
}

/**
 * Sorts two Objects By distance.
 */
MiningHelper.sortByDistance = function(distantObjectA, distantObjectB) {
	if (distantObjectA.distance > distantObjectB.distance)
		return 1;
	if (distantObjectA.distance < distantObjectB.distance)
		return -1;
		
	return 0;
}

/**
 * Gets the distance between two objects.
 */
MiningHelper.getDistance = function(coordsA, coordsB) {
	var a = Math.abs(coordsA.x - coordsB.x);
	var b = Math.abs(coordsA.y - coordsB.y);
	
	var cQuad = Math.pow(a, 2) + Math.pow(b, 2);
	return Math.floor(Math.sqrt(cQuad) * 100) / 100;
}

/**
 * Creates and Returns an array with comets.
 */
MiningHelper.buildCometArray = function() {
	this.comets = new Array();
	
	/* foreach system in mapData */
	for (var systemId in this.mapData) {
		var systemObj = this.mapData[systemId];

		if (systemObj.comets) {
			/* foreach comet in a system */
			for (var i = 0; i < systemObj.comets.length; i++) {
				/* copy the comet */
				var currentComet = new Object();
				for (var property in systemObj.comets[i])
					currentComet[property] = systemObj.comets[i][property];
				
				/* some additional informations */
				currentComet.systemId = systemId;
				currentComet.coordinates = this.config.generator.getCoordsBySystemId(systemId);
				currentComet.distance = this.getDistance(this.centeredSystemCoords, currentComet.coordinates);
				
				currentComet.events = this.searchEventsBySpotName(currentComet.name);
				this.addCountdownsFromEvents(currentComet);
				
				currentComet.r1 = Number(currentComet.r1);
				currentComet.r2 = Number(currentComet.r2);
				currentComet.r3 = Number(currentComet.r3);
				
				/* Refresh max resources */
				this.maxMetal = Math.max(currentComet.r1, this.maxMetal);
				this.maxCrystal = Math.max(currentComet.r2, this.maxCrystal);
				this.maxDeuTri = Math.max(currentComet.r3, this.maxDeuTri);
				
				this.comets.push(currentComet);
			}
		}
	}
	
	this.comets = this.comets.sort(this.sortByDistance);
}

/**
 * Creates and Returns an array with debris.
 */
MiningHelper.buildDebrisArray = function() {
	this.debris = new Array();
	
	/* foreach system in mapData */
	for (var systemId in this.mapData) {
		var systemObj = this.mapData[systemId];

		if (systemObj.debris) {
			/* foreach debris in a system */
			for (var debrisId in systemObj.debris) {
				//Workaround to remove Questplanets from the list (it is possible to farm quest planets from other players ??!!?)
				//it seems that the id ends with 11 ^.^
				if (String(debrisId).match("11$") == "11")
					continue;
			
				/* copy the comet */
				var currentDebris = new Object();
				for (var property in systemObj.debris[debrisId])
					currentDebris[property] = systemObj.debris[debrisId][property];
					
				currentDebris.id = debrisId;
				currentDebris.systemId = systemId;
				currentDebris.name = systemObj.planets[currentDebris.planet_id].planet_name;
				if (currentDebris.name == null)
					currentDebris.name = debrisId;
				currentDebris.r3 = 0;
				currentDebris.coordinates = this.config.generator.getCoordsBySystemId(systemId);
				currentDebris.distance = this.getDistance(this.centeredSystemCoords, currentDebris.coordinates);
				
				currentDebris.events = this.searchEventsBySpotName(currentDebris.name);
				this.addCountdownsFromEvents(currentDebris);
				
				currentDebris.r1 = Number(currentDebris.r1);
				currentDebris.r2 = Number(currentDebris.r2);
				
				/* Refresh max resources */
				this.maxMetal = Math.max(currentDebris.r1, this.maxMetal);
				this.maxCrystal = Math.max(currentDebris.r2, this.maxCrystal);
				this.maxDeuTri = Math.max(currentDebris.r3, this.maxDeuTri);
				
				this.debris.push(currentDebris);
			}
		}
	}
	
	this.debris = this.debris.sort(this.sortByDistance);
}

/**
 * Creates and Returns an array with Asteriods.
 * @Thanks to jessa for this method.
 */
MiningHelper.buildAsteroidArray = function() {
	this.asteroids = new Array();

	/* foreach system in mapData */
	for (var systemId in this.mapData) {
		var systemObj = this.mapData[systemId];

		if (systemObj.asteroids) {
			/* foreach asteroid in a system */
			for (var i = 0; i < systemObj.asteroids.length; i++) {
				/* copy the asteroid */
				var currentAsteroid = new Object();
				for (var property in systemObj.asteroids[i])
					currentAsteroid[property] = systemObj.asteroids[i][property];

				/* some additional informations */
				currentAsteroid.systemId = systemId;
				currentAsteroid.coordinates = this.config.generator.getCoordsBySystemId(systemId);
				currentAsteroid.distance = this.getDistance(this.centeredSystemCoords, currentAsteroid.coordinates);
				currentAsteroid.name = 'A-' + currentAsteroid.id;

				currentAsteroid.events = this.searchEventsBySpotName(currentAsteroid.name);
				this.addCountdownsFromEvents(currentAsteroid);
				
				currentAsteroid.r1 = Number(currentAsteroid.r1);
				currentAsteroid.r2 = Number(currentAsteroid.r2);
				currentAsteroid.r3 = Number(currentAsteroid.r3);
				
				/* Refresh max resources */
				this.maxMetal = Math.max(currentAsteroid.r1, this.maxMetal);
				this.maxCrystal = Math.max(currentAsteroid.r2, this.maxCrystal);
				this.maxDeuTri = Math.max(currentAsteroid.r3, this.maxDeuTri);

				this.asteroids.push(currentAsteroid);
			}
		}
	}

	this.asteroids = this.asteroids.sort(this.sortByDistance);
}

/**
 * Inserts each Asteroid as an list entry into the ListFrame
 */
MiningHelper.insertAsteroidListEntries = function() {
	var asteroidList = $("#impSpotFinder_asteroidList");
	
	for (var i = 0; i < this.asteroids.length; i++) {
		var currentAsteroid = this.asteroids[i];
		
		var link = this.createSpotLink(currentAsteroid, "a");
		var listEntry = this.wrapInListElement(link);
		
		asteroidList.append(listEntry);
	}
}

/**
 * Inserts each Debris as an list entry into the ListFrame
 */
MiningHelper.insertDebrisListEntries = function() {
	var debrisList = $("#impSpotFinder_debrisList");
	
	for (var i = 0; i < this.debris.length; i++) {
		var currentDebris = this.debris[i];
		
		var link = this.createSpotLink(currentDebris, "d");
		var listEntry = this.wrapInListElement(link);
		
		debrisList.append(listEntry);
	}
}

/**
 * Inserts each Comet as an list entry into the ListFrame
 */
MiningHelper.insertCometListEntries = function() {
	var cometList = $("#impSpotFinder_cometList");
	
	for (var i = 0; i < this.comets.length; i++) {
		var currentComet = this.comets[i];
		
		var link = this.createSpotLink(currentComet, "c");
		var listEntry = this.wrapInListElement(link);
		
		cometList.append(listEntry);
	}
}

/**
 * Creates a spot Link Element with the corresponding events
 */
MiningHelper.createSpotLink = function(spotObj, spotType) {
	var linkElement = document.createElement("a");
	
	var internalLinkElement = $(linkElement);
	internalLinkElement.text(spotObj.name);
	if (spotObj.events.length > 0) {
		internalLinkElement.css("font-weight", "bold");
		internalLinkElement.attr("class", "fontColorRace");
	}
	internalLinkElement.attr("href", "/fleetBase/mission/1/planetId/" + spotType + spotObj.id + "/m/301");
	
	//Show info box on mouse over
	internalLinkElement.bind('mouseover', {thisObj: this, spotObj: spotObj}, function(e) {
		e.data.thisObj.showSpotInfoBox(e.data.spotObj, unsafeWindow.mouseX, unsafeWindow.mouseY);
	});
	
	//Hide info box
	internalLinkElement.bind('mouseout', {thisObj: this}, function(e) {
		e.data.thisObj.hideTimer = window.setTimeout(e.data.thisObj.hideSpotInfoBox, 250);
	});
	
	return linkElement;
}

/**
 * Creates a list element around another DOM Element
 */
MiningHelper.wrapInListElement = function(wrappedElement) {
	var listElement = document.createElement("li");
	listElement.setAttribute("style", "list-style-type: disc;");
	listElement.appendChild(wrappedElement);
	
	return listElement;
}

/**
 * Hides the Spot Info box.
 */
MiningHelper.hideSpotInfoBox = function() {
	$("#impSpotFinder_spotInfo").css("display", "none");
}

/**
 * Shows the Spot Info box, and positions it to the given coordinates.
 */
MiningHelper.showSpotInfoBox = function(spotObj, x, y) {
	/**
	 * Converts the current value relative to the max value into an colored string between red and green.
	 */
	function intToRGBString(current, max) {
		var percent = current / max;
		var green = percent * 255;
		green = Math.round(green);
		var red = percent * 255;
		red = 255 - Math.round(red);
		
		return "rgb(" + red + "," + green + ",0)";
	}
	
	function createUnitRow(color, name, baseCargoCapacity, baseSpeed) {
		var cargoCapacity = baseCargoCapacity * (1 + (0.05 * MiningHelper.researches.cargoCapacity));
		
		var realDistance = 5;
		if (spotObj.distance <= 0)
			realSpeed = baseSpeed;
		else {
			realSpeed = baseSpeed * (1 + (0.1 * MiningHelper.researches.driveEngineering));
			realSpeed = Math.floor(realSpeed * 100) / 100;
			realDistance = realDistance + spotObj.distance;
		}
		
		//flightduration
		var flightDuration = Math.round(realDistance / ((realSpeed / 60) / 60));
		flightDuration = new Date((flightDuration * 1000) - (60 * 60 * 1000)); //Subtraktion in order to normalize GMT to UTC
		
		var recCount = Math.ceil(maxLoot / cargoCapacity);
		
		var html = new Array(
			"<tr>",
				"<td style='color: " + color + ";'>",
					name,
				"</td>",
				"<td>",
					recCount,
				"</td>",
				"<td>",
					maxLoot + "/" + recCount * cargoCapacity,
				"</td>",
				"<td>",
					flightDuration.format("HH:MM:ss"),
				"</td>",
			"</tr>"
		);
		
		return $(html.join(""));
	}
	
	//Prevent from hiding the InfoBox
	if (this.hideTimer)
		window.clearTimeout(this.hideTimer);
	
	//Fill the box with content related to spotObj
	var coordinates = spotObj.coordinates;
	var coordsLink = $("#spotInfo_coords");
	coordsLink.attr("href", "javascript: window.location = '/map/index?galaxyId=" + coordinates.galaxyId + "&xCoord=" + coordinates.x + "&yCoord=" + coordinates.y + "';");
	coordsLink.text("(" + coordinates.galaxyId + "|" + coordinates.x + "|" + coordinates.y + ")");
	$("#spotInfo_distance").text(spotObj.distance);
	
	var metalDOM = $("#spotInfo_resourceMetal");
	metalDOM.text(spotObj.r1);
	metalDOM.css("color", intToRGBString(spotObj.r1, this.maxMetal));
	
	var crystalDOM = $("#spotInfo_resourceCrystal");
	crystalDOM.text(spotObj.r2);
	crystalDOM.css("color", intToRGBString(spotObj.r2, this.maxCrystal));
	
	var deutriDOM = $("#spotInfo_resourceDeuTri");
	deutriDOM.text(spotObj.r3);
	deutriDOM.css("color", intToRGBString(spotObj.r3, this.maxDeuTri));
	
	var maxLoot = spotObj.r1 + spotObj.r2 + spotObj.r3;
	//recycle duration
	var recycleDurationPerCargoUnit = (Math.pow(0.5,MiningHelper.researches.recycling) * (60 * 60 * 1000)) / 500;
	var recycleDuration = (10 * 60 * 1000) + (Math.round(maxLoot * recycleDurationPerCargoUnit));
	recycleDuration = new Date(recycleDuration - (60 * 60 * 1000));
	$("#spotInfo_recycleDuration").text(recycleDuration.format("HH:MM:ss"));
	
	//Fleet data
	var fleetDataTable = $("#spotInfo_fleetData_tableBody");
	fleetDataTable.empty();
	if (this.playerSpecies == "terrans") {
		fleetDataTable.append(createUnitRow("#FFD800", $l("terranSmallRecycler"), 500, 12));
		fleetDataTable.append(createUnitRow("#FFD800", $l("terranBigRecycler"), 20000, 6));
	}
	
	if (this.playerSpecies == "titans") {
		fleetDataTable.append(createUnitRow("#2595FE", $l("titanRecycler"), 1000, 10));
	}
	
	if (this.playerSpecies == "xen") {
		fleetDataTable.append(createUnitRow("#5AFF00", $l("xenRecycler"), 800, 10));
	}
	
	//Reveal the event section if needed
	if (spotObj.events.length > 0) {
		$("#spotInfo_events").css("display", "block");
		
		var table = $("#spotInfo_events_tableBody");
		table.empty();
		//Render events list we do it with description
		for (var i = 0; i < spotObj.events.length; i++) {
			table.append(this.renderEvent(spotObj.events[i], spotObj.eventCountdowns[i]));
		}
	} else {
		$("#spotInfo_events").css("display", "none");
	}
	
	//Position and show the box
	var infoBox = $("#impSpotFinder_spotInfo");
	infoBox.css("display", "block");
	infoBox.css("left", (x + 20) + "px");
	infoBox.css("top", y + "px");
}

/**
 * Renders an event into DOM represenation and returns the row element (tr)
 */
MiningHelper.renderEvent = function(event, eventCountdown) {
	var html = new Array(
		"<tr>", 
			"<td>" + event[2] + "</td>", 
			"<td>" + event[event.length - 1] + "</td>", 
			"<td class='spotInfoCountDown'></td>",
		"</tr>"
	);
	
	var result = $(html.join(""));
	result.children(".spotInfoCountDown").append(eventCountdown);
	return result;
}

/**
 * Inserts the Html for the ResourceSpotList.
 */
MiningHelper.insertListFrameAsHtml = function() {
	insertHtml(new Array(
		"<div style='top: 5px; left: 5px; width: auto; display: block; z-index: 10100 ! important;' class='fontLeft dialog'>",
			"<div class='tLeft interface_dialog_tLeft'>",
				"<div style='background-position: right center;' class='tRight bgNoRepeat interface_dialog_tRight'></div>",
			"</div>",
			"<div class='mLeft bgYRepeat interface_dialog_mLeft' style='margin-top: -15px;'>",
				"<div class='mRight bgCenterRight bgYRepeat interface_dialog_mRight' style='padding-right: 15px;'>",
					"<ul>",
						"<li><b>" + $l('asteroids') + "</b>",
							"<ul id='impSpotFinder_asteroidList' style='margin-left: 1.4em;'>",
							"</ul>",
						"</li>",
						"<br />",
						"<li><b>" + $l('debris') + "</b>",
							"<ul id='impSpotFinder_debrisList' style='margin-left: 1.4em;'>",
							"</ul>",
						"</li>",
						"<br />",
						"<li><b>" + $l('comets') + "</b>",
							"<ul id='impSpotFinder_cometList' style='margin-left: 1.4em;'>",
							"</ul>",
						"</li>",
					"</ul>",
					"<br />",
					"<div style='font-size: 7px;'>MiningHelper - v0.0.6</div>",
				"</div>",
			"</div>",
			"<div class='bLeft interface_dialog_bLeft'>",
				"<div class='bRight bgNoRepeat bgCenterRight interface_dialog_bRight'></div>",
			"</div>",
		"</div>"
	));
}

/**
 * Inserts the Html for the ResourceSpotInfoBox.
 */
MiningHelper.insertInfoBoxFrameAsHtml = function() {
	insertHtml(new Array(
		"<div id='impSpotFinder_spotInfo' style='display: none; width: auto; z-index: 10100 ! important;' class='fontLeft dialog'>",
			"<div class='tLeft interface_dialog_tLeft'>",
				"<div style='background-position: right center;' class='tRight bgNoRepeat interface_dialog_tRight'></div>",
			"</div>",
			"<div class='mLeft bgYRepeat interface_dialog_mLeft' style='margin-top: -15px;'>",
				"<div class='mRight bgCenterRight bgYRepeat interface_dialog_mRight' style='padding-right: 15px;'>",
					"<div style='padding: 10px;' class='colorGrey'>",
						"<div>", 
							"<h1 class='fontSize12'>" + $l('resourceSpot') + "</h1>", 
							"<br />",
							"<table class='colorGrey fontSize10'>", 
								"<colgroup>", 
									"<col style='width: 150px;'/>", 
									"<col/>", 
								"</colgroup>", 
								"<tbody>", 
									"<tr>", 
										"<td>" + $l('coordinates') + ":</td>", 
										"<td><a id='spotInfo_coords'></a></td>", 
									"</tr>", 
									"<tr>", 
										"<td>" + $l('distance') + ":</td>", 
										"<td id='spotInfo_distance'></td>", 
									"</tr>", 
									"<tr>", 
										"<td colspan='2'>&nbsp;</td>", 
									"</tr>",
									"<tr>", 
										"<td>" + $l('metal') + ":</td>", 
										"<td id='spotInfo_resourceMetal'></td>", 
									"</tr>", 
									"<tr>", 
										"<td>" + $l('crystal') + ":</td>", 
										"<td id='spotInfo_resourceCrystal'></td>", 
									"</tr>", 
									"<tr>", 
										"<td>" + $l('deuterium') + "/" + $l('tritium') + ":</td>", 
										"<td id='spotInfo_resourceDeuTri'></td>", 
									"</tr>",
									"<tr>", 
										"<td>" + $l('recycleDuration') + ":</td>", 
										"<td id='spotInfo_recycleDuration'></td>", 
									"</tr>",	
								"</tbody>", 
							"</table>", 
							"<br />",
							"<br />",
							"<h1 class='fontSize12'>" + $l('fleetData') + "</h1>", 
							"<br />",
							"<table class='colorGrey fontSize10'>", 
								"<colgroup>", 
									"<col style='width: 100px;'/>", 
									"<col style='width: 60px;'/>",
									"<col style='width: 100px;'/>",
									"<col style='width: 75px;'/>",
								"</colgroup>", 
								"<tbody>",
									"<tr>",
										"<td style='font-weight: bold;'>" + $l('unit') + "</td>",
										"<td style='font-weight: bold;'>" + $l('count') + "</td>",
										"<td style='font-weight: bold;'>" + $l('cargoCapacity') + "</td>", 
										"<td style='font-weight: bold;'>" + $l('flightDuration') + "</td>",
									"</tr>",
								"</tbody>",
							"</table>",
							"<table class='colorGrey fontSize10'>", 
								"<colgroup>", 
									"<col style='width: 100px;'/>", 
									"<col style='width: 60px;'/>",
									"<col style='width: 100px;'/>",
									"<col style='width: 75px;'/>",
								"</colgroup>", 
								"<tbody id='spotInfo_fleetData_tableBody'>",
								"</tbody>",
							"</table>",
							"<div id='spotInfo_events' style='display: none;'>",
								"<br />",
								"<br />",
								"<h1 class='fontSize12'>" + $l('fleetEvents') + "</h1>", 
								"<br />",
								"<table class='colorGrey fontSize10'>", 
									"<colgroup>", 
										"<col style='width: 150px;'/>", 
										"<col style='width: 100px;'/>",
										"<col/>",
									"</colgroup>", 
									"<tbody>",
										"<tr>",
											"<td style='font-weight: bold;'>" + $l('event') + "</td>",
											"<td style='font-weight: bold;'>" + $l('from') + "</td>", 
											"<td style='font-weight: bold;'>" + $l('duration') + "</td>", 
										"</tr>",
									"</tbody>",
								"</table>",
								"<table class='colorGrey fontSize10'>", 
									"<colgroup>", 
										"<col style='width: 150px;'/>", 
										"<col style='width: 100px;'/>",
										"<col/>",
									"</colgroup>", 
									"<tbody id='spotInfo_events_tableBody'>",
									"</tbody>",
								"</table>",
							"</div>",
						"</div>",
					"</div>",
				"</div>",
			"</div>",
			"<div class='bLeft interface_dialog_bLeft'>",
				"<div class='bRight bgNoRepeat bgCenterRight interface_dialog_bRight'></div>",
			"</div>",
		"</div>"
	));
	
	//After inserting the html, we need to attach two events
	var infoBox = $("#impSpotFinder_spotInfo");
	infoBox.bind("mouseenter", {thisObj: this}, function(e) {
		window.clearTimeout(e.data.thisObj.hideTimer);
	});
	
	infoBox.bind("mouseleave", {thisObj: this}, function(e) {
		e.data.thisObj.hideTimer = window.setTimeout(e.data.thisObj.hideSpotInfoBox, 100);
	});
}

if (location.href.indexOf('researchCenter') > 0) {
	MiningHelper.writeResearches();
}

if (location.href.indexOf('map') > 0) {
	MiningHelper.initialize();
}

})();